import base64
import datetime
import hashlib
import random
import string
import time


def bs64_to_bytes(bs64_str):
    image_data = base64.b64decode(bs64_str)
    return image_data


def bs64_to_save_image(bs64_str, save_path):
    image_data = base64.b64decode(bs64_str)
    with open(save_path, 'wb') as f:
        f.write(image_data)


def images_to_bs64(img):
    bs64 = base64.b64encode(img)
    return bs64.decode('utf-8')


def get_now_time_string():
    """
        :return:
        :PS ：并发较高时尾部随机数增加
    """
    order_id = str(datetime.datetime.fromtimestamp(time.time())).replace("-", "").replace(" ", "").replace(":","").replace(".", "") + str(random.randint(100, 99999))
    return order_id


def getSha256(text):
    h = hashlib.sha256()
    h.update(text.encode())
    return h.hexdigest()


def selected_number_chrs(length):
    """
    返回length个随机数字字符串
    :param length:
    :return:
    """
    # 候选字符集,0-9
    chrs = string.digits
    result = ''.join(random.choice(chrs) for _ in range(length))
    return result


def get_router_list(app):
    exclude_li = ['/assets', '/docs/oauth2-redirect', '/v1/docs', '/v1/openapi.json', '/v1/redoc']
    for route in app.routes:
        if route.path not in exclude_li:
            print(route.path, route.name, route.tags, route)


def get_request_ip(request):
    """
    获取请求IP
    :param request:
    :return:
    """
    # print(request.headers)
    x_forwarded_for = request.headers.get('x-forwarded-for')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[-1].strip()
        return ip
    ip = request.headers.get('remote_addr')
    return ip or 'unknown'

